package com.yangyang.notepad;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import com.google.android.material.appbar.MaterialToolbar;

public class EditNoteFragment extends Fragment {
    // 定义常量
    private static final String SAVED_KEY_TITLE = "saved_title";
    private static final String SAVED_KEY_CONTENT = "saved_content";
    private static final String SAVED_KEY_INFO = "saved_info";

    private EditText titleEditText;
    private EditText contentEditText;
    private Note note;
    private ClipboardManager clipboardManager;
    private NoteDatabaseHelper databaseHelper;
    private boolean isNewNote = false;
    private TextView tvInfo;
    private UndoRedoHelper undoRedoHelper;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        clipboardManager = (ClipboardManager) requireActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        databaseHelper = new NoteDatabaseHelper(requireContext());
    }

    //创建并返回 Fragment 的视图层级
    //在 onCreate() 之后
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_edit_note, container, false);

        // 初始化视图
        titleEditText = view.findViewById(R.id.titleEditText);
        contentEditText = view.findViewById(R.id.contentEditText);
        tvInfo = view.findViewById(R.id.tv_info);

        // 获取传递的数据
        Bundle args = getArguments();
        if (args != null && args.containsKey("note")) {
            note = args.getParcelable("note");
            if (note != null) {
                titleEditText.setText(note.getTitle());
                contentEditText.setText(note.getContent());

                // 将光标移动到内容末尾
                contentEditText.setSelection(contentEditText.getText().length());

                // 判断是否是粘贴操作创建的新笔记（ID为null表示新笔记）
                isNewNote = note.getId() == null;
                //isNewNote = args.getBoolean("isNewNote", true); // 默认true更安全
            }
        } else {
            // 新建笔记
            note = new Note("", "");
            isNewNote = true;
        }

        undoRedoHelper = new UndoRedoHelper(contentEditText);

        setupNoteInfo(note); // 显示时间信息

//        // 设置菜单项点击监听
//        MaterialToolbar toolbar = view.findViewById(R.id.toolbar);
//        toolbar.setNavigationOnClickListener(v -> {
//            // 返回上一页面
//            Navigation.findNavController(view).navigateUp();
//        });
//
//        // 处理菜单点击（复制/粘贴）
//        toolbar.setOnMenuItemClickListener(item -> {
//            int id = item.getItemId();
//            if (id == R.id.menu_copy) {
//                handleCopy();
//                return true;
//            } else if (id == R.id.menu_paste) {
//                handlePaste();
//                return true;
//            }
//            return false;
//        });

        // 设置 Toolbar
        //ImageButton btnBack = view.findViewById(R.id.btn_back);
//        MaterialButton btnCopy = view.findViewById(R.id.btn_copy);
//        MaterialButton btnPaste = view.findViewById(R.id.btn_paste);
//        MaterialButton btnUndo = view.findViewById(R.id.btn_undo);

        // 绑定返回按钮事件
//        btnBack.setOnClickListener(v -> {
//            Navigation.findNavController(view).navigateUp();
//        });

        // 绑定复制按钮
//        btnCopy.setOnClickListener(v -> {
//            handleCopy();
//        });
        // 绑定粘贴按钮
//        btnPaste.setOnClickListener(v -> {
//            handlePaste();
//        });

//        btnUndo.setOnClickListener(v -> {
//            //titleEditText.setText();
//            //contentEditText.setText();
//        });

        return view;
    }

    private void handleCopy() {
        String textToCopy = contentEditText.getText().toString();
        if (!textToCopy.isEmpty()) {
            ClipData clip = ClipData.newPlainText("Note Content", textToCopy);
            clipboardManager.setPrimaryClip(clip);
            Toast.makeText(getActivity(), "已复制到剪贴板", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getActivity(), "没有内容可复制", Toast.LENGTH_SHORT).show();
        }
    }

    private void handlePaste() {
        if (clipboardManager.hasPrimaryClip()) {
            ClipData.Item item = clipboardManager.getPrimaryClip().getItemAt(0);
            String clipboardText = item.getText().toString();

            // 获取当前焦点视图
            View focusedView = requireActivity().getCurrentFocus();

            if (focusedView == contentEditText) {
                // 如果焦点在内容框
                int cursorPosition = contentEditText.getSelectionStart();
                // 在光标位置插入剪贴板内容
                contentEditText.getText().insert(cursorPosition, clipboardText);
                // 将光标移动到插入文本的末尾
                contentEditText.setSelection(cursorPosition + clipboardText.length());
            } else if (focusedView == titleEditText) {
                // 如果焦点在标题框
                int cursorPosition = titleEditText.getSelectionStart();
                titleEditText.getText().insert(cursorPosition, clipboardText);
                int newPosition = cursorPosition + clipboardText.length();
                titleEditText.setSelection(Math.min(newPosition, titleEditText.getText().length()));
            } else {
                // 默认添加到内容框
                contentEditText.append(clipboardText);
                contentEditText.setSelection(contentEditText.getText().length());
            }
            //contentEditText.getText().insert(contentEditText.getSelectionStart(), clipboardText);
        } else {
            Toast.makeText(getActivity(), "剪贴板为空", Toast.LENGTH_SHORT).show();
        }
    }

    private void setupNoteInfo(Note note) {
        if (note.getCreateTime() != null) {
            // 格式化时间（示例：2023-10-20 14:30）
            String createdAt = DateUtil.formatTime(note.getCreateTime());
            String updatedAt = DateUtil.formatTime(note.getUpdateTime());
            String updatedStr = TextUtils.equals(createdAt, updatedAt) ? "" : " 更新于 " + updatedAt;
            tvInfo.setText("创建于 " + createdAt + updatedStr);
        } else {
            tvInfo.setText("新笔记");
        }
    }

    //在视图创建完成后初始化控件和逻辑
    //在 onCreateView() 之后
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        MaterialToolbar toolbar = view.findViewById(R.id.toolbar);
        toolbar.setNavigationOnClickListener(v -> {
            Navigation.findNavController(view).navigateUp();
        });

        // 恢复临时状态（如果有）
        if (savedInstanceState != null) {
            titleEditText.setText(savedInstanceState.getString(SAVED_KEY_TITLE));
            contentEditText.setText(savedInstanceState.getString(SAVED_KEY_CONTENT));
            tvInfo.setText(savedInstanceState.getString(SAVED_KEY_INFO));
        }

        // 设置菜单点击监听
        toolbar.setOnMenuItemClickListener(item -> {
            int id = item.getItemId();

            if (id == R.id.menu_undo) {
                undoRedoHelper.undo(); // 撤销
                return true;
            }
            if (id == R.id.menu_redo) {
                undoRedoHelper.redo(); // 反撤销
                return true;
            }
            if (id == R.id.menu_copy) {
                handleCopy();
                return true;
            }
            if (id == R.id.menu_paste) {
                handlePaste();
                return true;
            }

            if (id == R.id.menu_clean) {
                contentEditText.setText("");
                Toast.makeText(requireContext(), "清空", Toast.LENGTH_SHORT).show();
                return true;
            }

            if (id == R.id.menu_delete) {
                databaseHelper.deleteNote(note.getId());
                Toast.makeText(requireContext(), "删除", Toast.LENGTH_SHORT).show();
                Navigation.findNavController(requireView()).navigateUp();
                return true;
            }

            return false;
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        // 保存当前编辑的内容
        saveNote();
    }

    private void saveNote() {
        String title = titleEditText.getText().toString();
        String content = contentEditText.getText().toString();
        if (note == null) {
            note = new Note(title, content);
        } else {
            note.setTitle(title);
            note.setContent(content);
        }
        if (isNewNote) {
            if (!title.isEmpty() || !content.isEmpty()) {
                note.setTitle(title);
                note.setContent(content);
                databaseHelper.addNote(note);
            }
        } else {
            note.setTitle(title);
            note.setContent(content);
            databaseHelper.updateNote(note);
        }
        // 返回上一页面
        //Navigation.findNavController(requireView()).navigateUp();
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 保存当前文本
        outState.putString(SAVED_KEY_TITLE, titleEditText.getText().toString());
        outState.putString(SAVED_KEY_CONTENT, contentEditText.getText().toString());
        outState.putString(SAVED_KEY_INFO, tvInfo.getText().toString());
    }
}
